<?php 

namespace App\HttpController;

use EasySwoole\Log\LoggerInterface;

class LogHandel implements LoggerInterface
{

    private $logDir;

    public function __construct(string $logDir = null)
    {
        if(empty($logDir)){
            $logDir = EASYSWOOLE_ROOT.'/Log';
        }
        $this->logDir = $logDir;
    }

    public function log(?string $msg,int $logLevel = self::LOG_LEVEL_INFO,string $path = 'system'):string
    {
        $date = date('Y-m-d H:i:s');
        $levelStr = $this->levelMap($logLevel);
        $filePath = $this->logDir."/{$path}/".date('Ym')."/";

        $fileName = "log_{$path}_".date('Ymd').".log";
        //判断目录是否存在
        if(!is_dir($filePath)){
        	mkdir($filePath, 0777, true);
        }
        $str = "请求日志:[{$date}] [{$levelStr}] : [{$msg}]".',内存大小'. round(memory_get_usage()/1024/1024, 2).'MB'.PHP_EOL;
        file_put_contents($filePath.$fileName,"{$str}",FILE_APPEND|LOCK_EX);
        return $str;
    }

    public function console(?string $msg,int $logLevel = self::LOG_LEVEL_INFO,string $category = 'console')
    {
        $date = date('Y-m-d H:i:s');
        $levelStr = $this->levelMap($logLevel);
        $temp = "自定义日志:[{$date}][{$category}][{$levelStr}]:[{$msg}]\n";
        fwrite(STDOUT,$temp);
    }

    private function levelMap(int $level)
    {
        switch ($level)
        {
            case self::LOG_LEVEL_INFO:
                return 'info';
            case self::LOG_LEVEL_NOTICE:
                return 'notice';
            case self::LOG_LEVEL_WARNING:
                return 'warning';
            case self::LOG_LEVEL_ERROR:
                return 'error';
            default:
                return 'unknown';
        }
    }
}
